const md5 = require('../js_sdk/js-md5/md5.min.js');
const getnow = Date.now || function() {
	return new Date().getTime();
};

export default {
	websiteUrl: 'http://api.yifeng.co/v1/',
	time:5,
	now: function() {
		let time = getnow();
		return Math.ceil(time / 1000)
	},
	setSign: function(options = []) {
		options.sort();
		let str = options.join("&");
		return md5(str);
	},
	checkLogin: function() {
		var info = uni.getStorageSync("userinfo");
		if (info.username == '' || typeof(info.username) == 'undefined' || info.token == '' || typeof(info.token) ==
			'undefined') {
			uni.reLaunch({
				url: "../login/login"
			})
		}
	},
	//网络请求
	req:function(options){
		//对参数进行处理
		console.log(this);
		let api = options.api ==undefined ?"":options.api;
		let timestamp = options.timestamp ==undefined ?"":options.timestamp;
		let data = options.data ==undefined ?{}:options.data;
		let header = options.header ==undefined ?{}:options.header;
		let method = options.method ==undefined ?"POST":options.method;
		return new Promise((reslove,reject)=>{
			uni.request({
				url: this.websiteUrl + api +"/?timestamp=" + timestamp,
				data: data,
				header: header,
				method: method,
				success: (res) => {
					if (res.data.errorcode == undefined) {
						uni.showToast({
							title: "请求异常",
							icon: "none",
							position: "bottom"
						})
						return;
					}
					//超时或者账号冻结
					if (res.data.errorcode  == 200000) {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							position: "bottom"
						})
						//退出当前登录
						uni.clearStorageSync('userinfo');
						setTimeout(()=>{
							uni.reLaunch({
								url: "../login/login"
							})
						},1000)
						return;
					}
					if (res.data.errorcode  > 0) {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							position: "bottom"
						})
						return;
					}
					console.log(res.data.errorcode);
					//发送成功
					if (res.data.errorcode  == 0) {
						reslove(res);
					}else{
						uni.showToast({
							title: "操作异常",
							icon: "none",
							position: "bottom"
						})
						return;
					}
					
				},
				fail: function() {
					uni.showToast({
						title: "接口异常",
						icon: "none",
						position: "bottom"
					})
				}
			})
		});
	}
}
